package com.zzyl.nursing.util;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;


public class IDCardUtils {

    /**
     * 解析生日为 LocalDateTime，例如：1967-12-13 00:00:00
     */
    public static LocalDateTime parseBirthDateTime(String idCard) {
        if (idCard == null || idCard.length() < 14) return null;

        try {
            String birthRaw = idCard.substring(6, 14); // yyyyMMdd
            LocalDate birth = LocalDate.parse(birthRaw, DateTimeFormatter.ofPattern("yyyyMMdd"));
            return birth.atStartOfDay();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 推导年龄
     */
    public static Integer deriveAge(String idCard) {
        LocalDateTime birthDT = parseBirthDateTime(idCard);
        if (birthDT == null) return null;

        return Period.between(birthDT.toLocalDate(), LocalDate.now()).getYears();
    }

    /**
     * 判断性别：0 男，1 女，2 未知
     */
    public static Integer identifySex(String idCard) {
        if (idCard == null || idCard.length() < 17) return 2;

        char c = idCard.charAt(16);
        if (!Character.isDigit(c)) return 2;

        int n = Character.getNumericValue(c);
        return (n % 2 == 1) ? 0 : 1;
    }
}